<!--
 * @Author: TANGB02 13233582+Ace-Tang@user.noreply.gitee.com
 * @Date: 2024-01-28 13:59:56
 * @LastEditors: TANGB02 13233582+Ace-Tang@user.noreply.gitee.com
 * @LastEditTime: 2024-03-06 11:41:31
 * @FilePath: \ycq\ycq\ycq1.0\src\components\modal\loginModel.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <a-modal
      v-model:open="open"
      @ok="handleOk"
      @cancel="handleCancel"
      style="width: 400px"
      cancelText="取消"
      okText="确定"
    >
      <a-form
        :model="formState"
        name="normal_login"
        class="login-form"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
        ref="formRef"
        :rules="rules"
      >
        <a-form-item name="phone">
          <a-input v-model:value="formState.phone" placeholder="电话号码">
            <template #prefix>
              <UserOutlined class="site-form-item-icon" />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item name="userPassword">
          <a-input-password
            v-model:value="formState.userPassword"
            placeholder="密码"
          >
            <template #prefix>
              <LockOutlined class="site-form-item-icon" />
            </template>
          </a-input-password>
        </a-form-item>
        <!-- 验证码 -->
        <div>
          <a-form-item name="vCode">
            <a-input
              v-model:value="vCode"
              placeholder="确输入验证码"
              class="codeText"
            ></a-input>
          </a-form-item>

          <VerificationCode
            style="
              position: relative;
              top: -60px;
              left: 170px;
              width: 120px;
              height: 40px;
            "
            @handleTxt="handleTxt"
            ref="codeDom"
          />
        </div>

        <a-form-item>
          <a-form-item name="remember" no-style>
            <a-checkbox v-model:checked="formState.remember"
              >记住密码</a-checkbox
            >
            <a href="/register" class="regist" @click="register">去注册></a>
          </a-form-item>
        </a-form-item>

        <a-form-item>
          <a-button
            type="primary"
            html-type="submit"
            class="login-form-button"
            style="left: 40%"
          >
            登录
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, defineProps, watch, defineEmits } from "vue";
import { useRouter } from "vue-router";
import { login } from "@/service/api.js";
import { UserOutlined, LockOutlined } from "@ant-design/icons-vue";
import LocalCatch from "@/utils/token.js";
import { message } from "ant-design-vue";
import VerificationCode from "@/components/canvas/verificationCode.vue";
import useLogin from "@/utils/statusManage.js";

const props = defineProps({
  lopen: { type: Boolean },
});
const router = useRouter();
const emits = defineEmits(["handleOpen"]);
const open = ref(false);
const formRef = ref();

// 正确验证码
const txt = ref("");
// 输入的验证码
const vCode = ref("");
//验证码输入错误后刷新
const codeDom = ref(null);
//初始化modal次数
let count = ref(0);
//登陆变量
const { setIsLogin } = useLogin();
// 监听模态框开关
watch(
  () => props.lopen,
  (newV, oldV) => {
    count.value += 1;
    open.value = newV;
    if (open.value) {
      // 第二次打开才能获取到子组件的dom节点
      if (count.value > 1) {
        codeDom.value.draw();
        console.log(codeDom.value);
      }
    }
  }
);

const closeModal = () => {
  formState.value = {};
  formRef.value.resetFields(); //清除校验红标
  open.value = false;
  emits("handleOpen", open.value);
  vCode.value = "";
};
// 点击确定或者取消关闭模态框
const handleOk = (e) => {
  closeModal();
};
const handleCancel = (e) => {
  closeModal();
};

//表单
const formState = ref({
  phone: "",
  userPassword: "",
  remember: false,
});
// 登录成功
const onFinish = async (values) => {
  console.log("Success:", values);

  // 校验执行回调
  formRef.value
    .validate()
    .then(async () => {
      // 校验通过
      //验证码通过

      const res = await login({
        phone: formState.value.phone,
        userPassword: formState.value.userPassword,
      });
      console.log(res);
      LocalCatch.setToken("userId", res.userId);
      // token
      if (res.code === 401) {
        vCode.value = "";
        message.error(res.msg);
        codeDom.value.draw();
      } else if (res.code === 1) {
        // 管理员登录
        LocalCatch.setToken("token", res.data);
        const token = LocalCatch.getToken("token");
        if (token) {
          setIsLogin(true);
          LocalCatch.setToken("roles", "admin");
          LocalCatch.setToken("userName", res.msg);
          message.success("登录成功");
          closeModal();
          router.push({ name: "managerDefault" });
        }
      } else {
        // 用户登录
        LocalCatch.setToken("token", res.data);
        const token = LocalCatch.getToken("token");
        if (token) {
          message.success("登录成功");
          setIsLogin(true);
          LocalCatch.setToken("roles", "user");
          LocalCatch.setToken("userName", res.msg);
  console.log(values.phone);         
          LocalCatch.setToken("phone", values.phone);
          closeModal();
        }
      }
    })
    .catch((error) => {});
};
// 登陆失败
const onFinishFailed = (errorInfo) => {
  console.log("Failed:", errorInfo);

  //  点击登录后输入验证码错误刷新验证码
  if (vCode.value.toLowerCase() !== txt.value.toLowerCase()) {
    codeDom.value.draw();
  }
};
// 获取正确的验证码
const handleTxt = (text) => {
  txt.value = text;
};
// 电话校验
const validatorUserPhone = (rule, value) => {
  if (!/^[1][3-9][0-9]{9}$/.test(value)) {
    return Promise.reject("请输入正确格式的手机号！");
  } else {
    return Promise.resolve();
  }
};
// 密码校验
const validatorUserPwd = (rule, value) => {
  if (!value) {
    return Promise.reject("请输入密码");
  }
  if (
    !/^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$)([^\u4e00-\u9fa5\s]){6,20}$/.test(
      value
    )
  ) {
    // 默认密码
    if (value === "123456") {
      return Promise.resolve();
    } else
      return Promise.reject(
        "请输入6-20位英文字母、数字或者符号(除空格),且字母、数字和标点符号至少包含两种"
      );
  } else {
    return Promise.resolve();
  }
};

// 验证码校验
const validatorvVCode = (rule, value) => {
  if (vCode.value.toLowerCase() !== txt.value.toLowerCase()) {
    return Promise.reject("请输入正确的验证码");
  } else return Promise.resolve();
};
// 校验规则
const rules = {
  phone: [{ validator: validatorUserPhone, required: true }],
  userPassword: [{ required: true, validator: validatorUserPwd }],
  vCode: [{ required: true, validator: validatorvVCode }],
};
</script>
<style scoped>
.codeErr {
  display: none;
  position: relative;
  top: -28px;
  color: #ff4d4f;
  font-size: 14px;
}
.codeText {
  width: 130px;
}
.regist {
  color: #a9a9a9;
  position: relative;
  font-size: 12px;
  float: right;
  margin-top: 3px;
}
.regist:hover {
  color: #1677ff;
}
#components-form-demo-normal-login .login-form {
  max-width: 300px;
}
#components-form-demo-normal-login .login-form-forgot {
  float: right;
}
#components-form-demo-normal-login .login-form-button {
  width: 100%;
}
.ant-form {
  margin: 50px 20px 30px 20px;
  padding: 5px 10px;
}
</style>
